'use strict';

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const {
    page = 1,
    pageSize = 10,
    type = '',      // 任务类型筛选
    status = '',    // 任务状态筛选
    audit_status = '', // 审核状态筛选
    keyword = '',   // 关键词搜索
    userId = ''     // 用户ID筛选
  } = event;

  try {
    let where = {};
    
    // 筛选条件
    if (type && type !== 'all') where.type = type;
    if (status) where.status = status;
    if (audit_status) where.audit_status = audit_status;
    if (userId) where.publisher_id = userId;
    
    if (keyword) {
      // 支持标题/描述/发布者模糊搜索
      where = {
        ...where,
        $or: [
          { title: new RegExp(keyword, 'i') },
          { description: new RegExp(keyword, 'i') },
          { publisher_name: new RegExp(keyword, 'i') }
        ]
      };
    }

    // 分页查询
    const collection = db.collection('taskList');
    const totalRes = await collection.where(where).count();
    const total = totalRes.total;

    const res = await collection
      .where(where)
      .orderBy('publish_time', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    // 字段映射：确保审核状态正确返回
    const mappedData = res.data.map(item => ({
      _id: item._id,
      id: item._id,
      type: item.type,
      title: item.title,
      description: item.description,
      reward: item.reward,
      status: item.status,
      publisher_id: item.publisher_id,
      publisher_name: item.publisher_name || item.user_name || '未知用户',
      user_name: item.user_name || item.publisher_name || '未知用户',
      publisher: {
        nickname: item.publisher_name || item.user_name || '未知用户',
        avatar: item.publisher_avatar
      },
      publish_time: item.publish_time,
      publishTime: item.publish_time,
      // 审核相关字段
      audit_status: item.audit_status || 'pending',
      audit_time: item.audit_time,
      audit_admin: item.audit_admin,
      reject_reason: item.reject_reason || '',
      // 其他字段
      isUrgent: item.is_urgent || false,
      tags: item.tags || [],
      pickupAddress: item.pickup_address || '',
      deliveryAddress: item.delivery_address || '',
      expectedDeliveryTime: item.expected_time || '',
      itemName: item.item_name || '',
      selectedCategory: item.selected_category || '',
      selectedCondition: item.selected_condition || '',
      contactName: item.contact_name || '',
      contactPhone: item.contact_phone || '',
      images: item.images || [],
      duration: item.duration || 0,
      views: item.views || 0,
      update_time: item.update_time
    }));

    console.log('[getTaskListWithUser] where:', where, 'total:', total, 'data.length:', mappedData.length);

    return {
      code: 200,
      msg: 'success',
      data: mappedData,
      total: total || 0
    };
  } catch (error) {
    console.error('获取任务列表失败:', error);
    return {
      code: 500,
      msg: '获取任务列表失败',
      data: [],
      total: 0
    };
  }
};
